package org.psyduck.admin.dict.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.psyduck.admin.dict.eneity.Dict;
import org.psyduck.admin.dict.service.DictService;
import org.psyduck.admin.dictitems.eneity.DictItems;
import org.psyduck.admin.dictitems.service.DictItemsService;
import org.psyduck.common.constant.Constants;
import org.psyduck.common.entity.DataMap;
import org.psyduck.common.model.PageJsonBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("dict")
public class DictController {

    @Autowired
    DictService dictService;

    @Autowired
    DictItemsService dictItemsService;

    @RequestMapping("list")
    public PageJsonBean list(Page page,Dict dict){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc(Constants.BaseEntity.CREATE_DATE);
        queryWrapper.select("id","dict_type","desc_ribe","type","remarks","sort");
        if(StrUtil.isNotBlank(dict.getType())){
            queryWrapper.like("type",dict.getType());
        }
        if(StrUtil.isNotBlank(dict.getDictType())){
            queryWrapper.like("dict_type",dict.getDictType());
        }
        return PageJsonBean.success(dictService.page(page,queryWrapper));
    }

    @CacheEvict(value = "admin" ,key = "'getDictItems'")
    @PreAuthorize("hasAuthority('dict:save')")
    @RequestMapping("save")
    public String save(Dict dict){
        dictService.saveOrUpdate(dict);
        return dict.getId();
    }

    @CacheEvict(value = "admin" ,key = "'getDictItems'")
    @PreAuthorize("hasAuthority('dict:delete')")
    @RequestMapping("delete")
    public Boolean delete(String id){
        dictItemsService.remove(new QueryWrapper<DictItems>().eq("dict_id",id));
        return dictService.removeById(id);
    }

    @RequestMapping("getDictByType")
    public List<DictItems> getDictByType(String type){
        Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("type", type));
        return dictItemsService.list(new QueryWrapper<DictItems>().eq("dict_id", dict.getId()));
    }

    @Cacheable(value = "admin" ,key = "methodName")
    @RequestMapping("getDictItems")
    public List<DataMap> getDictItems(){
        return dictService.getDao().getDictItems();
    }

    @RequestMapping("getSort")
    public Integer getSort(){
        Integer sort = dictService.getDao().getSort();
        if(null == sort){
            return 10;
        }
        return sort;
    }

}
